import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  ClassSerializerInterceptor,
} from '@nestjs/common';
import { MenuService } from './menu.service';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { ApiOperation } from '@nestjs/swagger';
import { User } from 'src/auth/decorator/user.decorator';
import { UserEntity } from 'src/user/entities/user.entity';
import { BusinessException } from 'src/common/filter/business-exception/business.exception';
import { getHomeMenu } from 'utils/tools/menuTransform';

@Controller('menu')
export class MenuController {
  constructor(private readonly menuService: MenuService) {}
  validParam(dto: CreateMenuDto | UpdateMenuDto) {
    if (dto.name && dto.name.length > 8)
      throw new BusinessException('菜单名称不能超过8位');
  }
  @Post()
  create(@Body() createMenuDto: CreateMenuDto, @User() user: UserEntity) {
    this.validParam(createMenuDto);
    return this.menuService.create(createMenuDto, user);
  }
  @ApiOperation({ summary: '根据权限获取菜单列表' })
  @UseInterceptors(ClassSerializerInterceptor)
  @Get()
  async findAll(@User() user: UserEntity) {
    const list = await this.menuService.findAll(user);
    const res = getHomeMenu(list);
    return res;
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.menuService.findOne(+id);
  }

  @Patch(':id')
  update(
    @Param('id') id: string,
    @Body() updateMenuDto: UpdateMenuDto,
    @User() user: UserEntity,
  ) {
    this.validParam(updateMenuDto);
    return this.menuService.update(id, updateMenuDto, user);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.menuService.remove(+id);
  }
}
